package com.pd.modules.common;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipeConnection
{
	private ObjectOutputStream mObjectWriter;
	private ObjectInputStream mObjectReader;

	private boolean mReady = false;

	public void stop()
	{
		try
		{
			mObjectReader.close();
		} catch (IOException e){}
	}
	
	public PipeConnection()
	{

		try
		{
			PipedOutputStream out = new PipedOutputStream();
			PipedInputStream in = new PipedInputStream(out);

			mObjectWriter = new ObjectOutputStream(out);
			mObjectReader = new ObjectInputStream(in);
		} catch (IOException e)
		{
			e.printStackTrace();
			return;
		}

		mReady = true;
	}

	public boolean sendMessage(Message _message)
	{
		if (!mReady)
			return false;

		try
		{
			mObjectWriter.writeObject(_message);
			mObjectWriter.flush();
		} catch (IOException e)
		{
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public Message readMessage()
	{
		Message tmpMessage = null;

		if (!mReady)
			return tmpMessage;

		try
		{
			tmpMessage = (Message) mObjectReader.readObject();
		} catch (IOException e)
		{
			//e.printStackTrace();
		} catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}

		return tmpMessage;
	}

}
